package com.article.controller.system;

import com.article.dto.ReturnError;
import com.article.enums.ReturnInfoEnum;
import com.article.model.ArticleInfo;
import com.article.model.ArticleType;
import com.article.service.ArticleInfoService;
import com.article.service.ArticleTypeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by Administrator on 2017/5/4.
 */
@RestController()
@RequestMapping("/refresh")
public class RefreshController {
    private final static Logger logger = LoggerFactory.getLogger(RefreshController.class);

    @Autowired
    private ArticleTypeService articleTypeService;
    @Autowired
    private ArticleInfoService articleInfoService;

    @RequestMapping(value = "/selfRefresh", method = RequestMethod.POST)
    private ReturnError refresh(HttpServletRequest request) {
        try {
            ServletContext application = request.getSession().getServletContext();

            List<ArticleType> articleTypeList = articleTypeService.listCount();// 查询文章类别以及文章的数量
            application.setAttribute("articleTypeCount", articleTypeList);

            List<ArticleInfo> articleInfoList = articleInfoService.listCount();//按日期查询文章数量
            application.setAttribute("articleCount", articleInfoList);
            logger.info("手动刷新缓存");
            return new ReturnError(false, ReturnInfoEnum.SUCCESS.getType(), ReturnInfoEnum.SUCCESS.getInfo(), null);
        } catch (Exception e) {
            logger.info(ReturnInfoEnum.ERROR.getInfo(), e);
            return new ReturnError(true, ReturnInfoEnum.ERROR.getType(), ReturnInfoEnum.ERROR.getInfo(), null);
        }
    }
}
